import axios from 'axios'
import { getToken, setToken, removeToken, getUuid, setUuid } from '@/utils/auth'
import { Loading, Message } from 'element-ui'
// import global_ from '@/utils/global.vue'
import store from '@/store'
// import router from '@/router'
import Fingerprint2 from 'fingerprintjs2'

var ResponseCodeEnum = {}
ResponseCodeEnum.SUCCESS = '200' // 操作成功
ResponseCodeEnum.TOKEN_EXPIRED = '401' // token已过期
ResponseCodeEnum.TOKEN_COVER = '402' // token被覆盖
ResponseCodeEnum.TOKEN_ILLEGAL = '403' // token非法
ResponseCodeEnum.TOKEN_EMPTY = '405' // token为空
ResponseCodeEnum.PERMISSION_ERROR = '406' // 权限不够
ResponseCodeEnum.URL_ERROR = '407' // URL错误
ResponseCodeEnum.SERVER_INTERNAL_ERROR = '500'// 服务器内部错误

var uuid
new Fingerprint2().get((fingerprint) => {
  uuid = fingerprint
})

export const UploadDownload = {
  upload: 'http://localhost:9090/yfuwebsite/upload/upload',
  download: 'http://192.168.62.171:9000/operFile/download'
}

// 创建axios实例
const service = axios.create({
  // baseURL: global_.isLocalServer ? 'http://localhost:8080' : 'http://localhost:9001', // api的base_url
  // timeout: 10000                  // 请求超时时间
})

service.defaults.headers['Content-Type'] = 'application/json;charset=U8'

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['ACCESS_TOKEN'] = getToken() // 让每个请求携带自定义token
    config.headers['UUID'] = getUuid()
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.statusCode !== ResponseCodeEnum.SUCCESS) {
      // 重新登录
      if (res.statusCode === ResponseCodeEnum.TOKEN_EXPIRED || res.statusCode === ResponseCodeEnum.TOKEN_COVER || res.statusCode === ResponseCodeEnum.TOKEN_ILLEGAL || res.statusCode === ResponseCodeEnum.TOKEN_EMPTY) {
        removeToken()
        location.reload()// 为了重新实例化vue-router对象 避免bug
        Message({
          'message': res.msg,
          'type': 'warning',
          'duration': 2000
        })
        return Promise.reject(new Error('error'))
      } else {
        return response
      }
    } else {
      return response
    }
  },
  error => {
    console.log('err' + error)// for debug
    return Promise.reject(error)
  }
)

export default service

export function yfuPost (baseURL, url, param, then, error) {
  if (url === '/user/login') {
    param.uuid = uuid
  }

  let loadingInstance = Loading.service({ fullscreen: true })
  // service.post(url, param, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then((response) => {
  service.post((baseURL + url), param).then((response) => {
    loadingInstance.close()
    let data = response.data
    if (data.statusCode === ResponseCodeEnum.SUCCESS) {
      if (url === '/user/login') {
        store.commit('SET_TOKEN', data.token)
        console.log('token0:' + getToken())
        setToken(data.token)
        // console.log('token1:' + getToken())
        // setToken(data.token)

        store.commit('SET_UUID', uuid)
        setUuid(uuid)

        store.commit('SET_ID', data.data.id)
        store.commit('SET_USERNAME', data.data.userName)
        store.commit('SET_TRUENAME', data.data.trueName)
        store.commit('SET_MOBILE', data.data.mobile)
        store.commit('SET_DETAILADDRESS', data.data.detailAddress)
        store.commit('SET_QQ', data.data.qq)
        store.commit('SET_EMAIL', data.data.email)
        store.commit('SET_WECHAT', data.data.wechat)
      }
      then(data.data)
    } else if (data.statusCode === ResponseCodeEnum.TOKEN_EXPIRED || data.statusCode === ResponseCodeEnum.TOKEN_COVER || data.statusCode === ResponseCodeEnum.TOKEN_ILLEGAL || data.statusCode === ResponseCodeEnum.TOKEN_EMPTY) {
      then(data.data)
    } else if (data.statusCode === ResponseCodeEnum.PERMISSION_ERROR || data.statusCode === ResponseCodeEnum.URL_ERROR) {
      then(data.data)
      Message({
        'message': data.msg,
        'type': 'error',
        'duration': 2000
      })
    } else {
      console.log(data.msg)
      Message({
        'message': data.msg,
        'type': 'error',
        'duration': 2000
      })
    }
  }).catch(() => {
    loadingInstance.close()
    console.log('系统异常，请联系管理员')
    Message({
      'message': '系统异常，请联系管理员',
      'type': 'error',
      'duration': 2000
    })
  })
}

export function tfGet (url, then, error) {
  let loadingInstance = Loading.service({ fullscreen: true })
  service.get(url).then((response) => {
    loadingInstance.close()
    let data = response.data
    if (data.statusCode === ResponseCodeEnum.SUCCESS) {
      if (url === '/static/user.json') {
        store.commit('SET_TOKEN', data.token)
        console.log('token0:' + getToken())
        setToken(data.token)
        // console.log('token1:' + getToken())
        // setToken(data.token)

        store.commit('SET_UUID', uuid)
        setUuid(uuid)

        store.commit('SET_ID', data.data.id)
        store.commit('SET_USERNAME', data.data.userName)
        store.commit('SET_TRUENAME', data.data.trueName)
        store.commit('SET_MOBILE', data.data.mobile)
        store.commit('SET_DETAILADDRESS', data.data.detailAddress)
        store.commit('SET_QQ', data.data.qq)
        store.commit('SET_EMAIL', data.data.email)
        store.commit('SET_WECHAT', data.data.wechat)
      }
      then(data.data)
    } else if (data.statusCode === ResponseCodeEnum.TOKEN_EXPIRED || data.statusCode === ResponseCodeEnum.TOKEN_COVER || data.statusCode === ResponseCodeEnum.TOKEN_ILLEGAL || data.statusCode === ResponseCodeEnum.TOKEN_EMPTY) {
      then(data.data)
    } else if (data.statusCode === ResponseCodeEnum.PERMISSION_ERROR || data.statusCode === ResponseCodeEnum.URL_ERROR) {
      then(data.data)
      Message({
        'message': data.msg,
        'type': 'error',
        'duration': 2000
      })
    } else {
      console.log(data.msg)
      Message({
        'message': data.msg,
        'type': 'error',
        'duration': 2000
      })
    }
  }).catch(() => {
    loadingInstance.close()
    console.log('系统异常，请联系管理员')
    Message({
      'message': '系统异常，请联系管理员',
      'type': 'error',
      'duration': 2000
    })
  })
}
